import { CSSProperties, useContext, useEffect, useState } from 'react';
import { Select } from 'antd';
import { DetailContext } from '@/biz-components/claim-items/components/DetailContext';

/**
 * 选项需要通过接口查询的下拉选择框
 * */
export function Selector<T>(props: {
  value: T;
  onChange: (value: T) => void;
  multiple?: boolean;
  dataSource:
    | (() => Promise<Array<{ name: string; value: string }>>)
    | Array<{ name: string; value: string }>;
  disabled?: boolean;
  style?: CSSProperties;
  showSearch?: boolean;
  valueInLabel?: boolean;
}) {
  const { multiple = false, valueInLabel = false } = props;
  const [options, setOptions] = useState<Array<{ name: string; value: string }>>([]);
  const detailMode = useContext(DetailContext);
  useEffect(
    function () {
      if (typeof props.dataSource === 'function') {
        props.dataSource().then(setOptions);
      } else {
        setOptions(props.dataSource);
      }
    },
    [props.dataSource],
  );

  if (detailMode) {
    let name = options.find((item) => item.value === ((props.value as unknown) as string))?.name || '';
    // @ts-ignore
    return <span>{name || props.value}</span>;
  }

  return (
    <Select<any>
      showSearch={props.showSearch}
      optionFilterProp={'children'}
      disabled={props.disabled}
      value={props.value}
      onChange={props.onChange}
      mode={multiple ? 'multiple' : undefined}
      allowClear
      style={{
        minWidth: 100,
        ...props.style,
      }}
    >
      {options.map((item) => (
        <Select.Option key={item.value} value={item.value}>
          {valueInLabel ? `${item.value}-${item.name}` : item.name}
        </Select.Option>
      ))}
    </Select>
  );
}
